home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60rt.lha / Vim / vim60 / tools / xcmdsrv_client.c < prev   
Encoding:
C/C++ Source or Header  |  2001-09-02  |  13.3 KB  |  579 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved    by Bram Moolenaar
  4.  * X-Windows communication by Flemming Madsen
  5.  *
  6.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  7.  * Do ":help credits" in Vim to see a list of people who contributed.
  8.  * See README.txt for an overview of the Vim source code.
  9.  *
  10.  * Client for sending commands to an '+xcmdsrv' enabled vim.
  11.  * This is mostly a de-Vimified version of if_xcmdsrv.c in vim.
  12.  * See that file for a protocol specification.
  13.  *
  14.  * You can make a test program with a Makefile like:
  15.  *  xcmdsrv_client: xcmdsrv_client.c
  16.  *    cc -o $@ -g -DMAIN -I/usr/X11R6/include -L/usr/X11R6/lib $< -lX11
  17.  *
  18.  */
  19.  
  20. #include <stdio.h>
  21. #include <string.h>
  22. #ifdef HAVE_SELECT
  23. #include <sys/time.h>
  24. #include <sys/types.h>
  25. #include <unistd.h>
  26. #else
  27. #include <sys/poll.h>
  28. #endif
  29. #include <X11/Intrinsic.h>
  30. #include <X11/Xatom.h>
  31.  
  32. #define __ARGS(x) x
  33.  
  34. /* Client API */
  35. char * sendToVim __ARGS((Display *dpy, char *name, char *cmd, int asKeys));
  36.  
  37. #ifdef MAIN
  38. /* A sample program */
  39. main(int argc, char **argv)
  40. {
  41.     char *res;
  42.  
  43.     if (argc == 4)
  44.     {
  45.     if ((res = sendToVim(XOpenDisplay(NULL),
  46.                  argv[2], argv[3], argv[1][0] != 'e')) != NULL)
  47.         puts(res);
  48.     exit(0);
  49.     }
  50.     else
  51.     fprintf(stderr, "Usage: %s {k|e} <server> <command>", argv[0]);
  52.  
  53.     exit(1);
  54. }
  55. #endif
  56.  
  57. /*
  58.  * Maximum size property that can be read at one time by
  59.  * this module:
  60.  */
  61.  
  62. #define MAX_PROP_WORDS 100000
  63.  
  64. /*
  65.  * Forward declarations for procedures defined later in this file:
  66.  */
  67.  
  68. static int    x_error_check __ARGS((Display *dpy, XErrorEvent *error_event));
  69. static int    AppendPropCarefully __ARGS((Display *display,
  70.             Window window, Atom property, char *value, int length));
  71. static Window    LookupName __ARGS((Display *dpy, char *name,
  72.             int delete, char **loose));
  73. static int    SendInit __ARGS((Display *dpy));
  74. static char    *SendEventProc __ARGS((Display *dpy, XEvent *eventPtr,
  75.                       int expect));
  76. static int    IsSerialName __ARGS((char *name));
  77.  
  78. /* Private variables */
  79. static Atom    registryProperty = None;
  80. static Atom    commProperty = None;
  81. static Window    commWindow = None;
  82. static int    got_x_error = FALSE;
  83.  
  84.  
  85. /*
  86.  * sendToVim --
  87.  *    Send to an instance of Vim via the X display.
  88.  *
  89.  * Results:
  90.  *    A string with the result or NULL. Caller must free if non-NULL
  91.  */
  92.  
  93.     char *
  94. sendToVim(dpy, name, cmd, asKeys)
  95.     Display    *dpy;            /* Where to send. */
  96.     char    *name;            /* Where to send. */
  97.     char    *cmd;            /* What to send. */
  98.     int        asKeys;            /* Interpret as keystrokes or expr ? */
  99. {
  100.     Window        w;
  101.     Atom        *plist;
  102.     XErrorHandler   old_handler;
  103. #define STATIC_SPACE 500
  104.     char        *property, staticSpace[STATIC_SPACE];
  105.     int            length;
  106.     int            res;
  107.     static int        serial = 0;    /* Running count of sent commands.
  108.                  * Used to give each command a
  109.                  * different serial number. */
  110.     XEvent        event;
  111.     XPropertyEvent  *e = (XPropertyEvent *)&event;
  112.     time_t        start;
  113.     char        *result;
  114.     char        *loosename = NULL;
  115.  
  116.     if (commProperty == None && dpy != NULL)
  117.     {
  118.     if (SendInit(dpy) < 0)
  119.         return NULL;
  120.     }
  121.  
  122.     /*
  123.      * Bind the server name to a communication window.
  124.      *
  125.      * Find any survivor with a serialno attached to the name if the
  126.      * original registrant of the wanted name is no longer present.
  127.      *
  128.      * Delete any lingering names from dead editors.
  129.      */
  130.  
  131.     old_handler = XSetErrorHandler(x_error_check);
  132.     while (TRUE)
  133.     {
  134.     got_x_error = FALSE;
  135.     w = LookupName(dpy, name, 0, &loosename);
  136.     /* Check that the window is hot */
  137.     if (w != None)
  138.     {
  139.         plist = XListProperties(dpy, w, &res);
  140.         XSync(dpy, False);
  141.         if (plist != NULL)
  142.         XFree(plist);
  143.         if (got_x_error)
  144.         {
  145.         LookupName(dpy, loosename ? loosename : name,
  146.                /*DELETE=*/TRUE, NULL);
  147.         continue;
  148.         }
  149.     }
  150.     break;
  151.     }
  152.     if (w == None)
  153.     {
  154.     fprintf(stderr, "no registered server named %s\n", name);
  155.     return NULL;
  156.     }
  157.     else if (loosename != NULL)
  158.     name = loosename;
  159.  
  160.     /*
  161.      * Send the command to target interpreter by appending it to the
  162.      * comm window in the communication window.
  163.      */
  164.  
  165.     length = strlen(name) + strlen(cmd) + 10;
  166.     if (length <= STATIC_SPACE)
  167.     property = staticSpace;
  168.     else
  169.     property = (char *) malloc((unsigned) length);
  170.  
  171.     serial++;
  172.     sprintf(property, "%c%c%c-n %s%c-s %s",
  173.               0, asKeys ? 'k' : 'c', 0, name, 0, cmd);
  174.     if (name == loosename)
  175.     free(loosename);
  176.     if (!asKeys)
  177.     {
  178.     /* Add a back reference to our comm window */
  179.     sprintf(property + length, "%c-r %x %d", 0, (uint) commWindow, serial);
  180.     length += strlen(property + length + 1) + 1;
  181.     }
  182.  
  183.     res = AppendPropCarefully(dpy, w, commProperty, property, length + 1);
  184.     if (length > STATIC_SPACE)
  185.     free(property);
  186.     if (res < 0)
  187.     {
  188.     fprintf(stderr, "Failed to send command to the destination program\n");
  189.     return NULL;
  190.     }
  191.  
  192.     if (asKeys) /* There is no answer for this - Keys are sent async */
  193.     return NULL;
  194.  
  195.  
  196.     /*
  197.      * Enter a loop processing X events & pooling chars until we see the result
  198.      */
  199.  
  200. #define SEND_MSEC_POLL 50
  201.  
  202.     time(&start);
  203.     while ((time((time_t *) 0) - start) < 60)
  204.     {
  205.     /* Look out for the answer */
  206. #ifndef HAVE_SELECT
  207.     struct pollfd   fds;
  208.  
  209.     fds.fd = ConnectionNumber(dpy);
  210.     fds.events = POLLIN;
  211.     if (poll(&fds, 1, SEND_MSEC_POLL) < 0)
  212.         break;
  213. #else
  214.     fd_set        fds;
  215.     struct timeval  tv;
  216.  
  217.     tv.tv_sec = 0;
  218.     tv.tv_usec =  SEND_MSEC_POLL * 1000;
  219.     FD_ZERO(&fds);
  220.     FD_SET(ConnectionNumber(dpy), &fds);
  221.     if (select(ConnectionNumber(dpy) + 1, &fds, NULL, NULL, &tv) < 0)
  222.         break;
  223. #endif
  224.     while (XEventsQueued(dpy, QueuedAfterReading) > 0)
  225.     {
  226.         XNextEvent(dpy, &event);
  227.         if (event.type == PropertyNotify && e->window == commWindow)
  228.         if ((result = SendEventProc(dpy, &event, serial)) != NULL)
  229.             return result;
  230.     }
  231.     }
  232.     return NULL;
  233. }
  234.  
  235.  
  236. /*
  237.  * SendInit --
  238.  *    This procedure is called to initialize the
  239.  *    communication channels for sending commands and
  240.  *    receiving results.
  241.  */
  242.  
  243.     static int
  244. SendInit(dpy)
  245.     Display *dpy;
  246. {
  247.     XErrorHandler old_handler;
  248.  
  249.     /*
  250.      * Create the window used for communication, and set up an
  251.      * event handler for it.
  252.      */
  253.     old_handler = XSetErrorHandler(x_error_check);
  254.     got_x_error = FALSE;
  255.  
  256.     commProperty = XInternAtom(dpy, "Comm", False);
  257.     /* Change this back to "InterpRegistry" to talk to tk processes */
  258.     registryProperty = XInternAtom(dpy, "VimRegistry", False);
  259.  
  260.     if (commWindow == None)
  261.     {
  262.     commWindow =
  263.         XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy),
  264.                 getpid(), 0, 10, 10, 0,
  265.                 WhitePixel(dpy, DefaultScreen(dpy)),
  266.                 WhitePixel(dpy, DefaultScreen(dpy)));
  267.     XSelectInput(dpy, commWindow, PropertyChangeMask);
  268.     }
  269.  
  270.     XSync(dpy, False);
  271.     (void) XSetErrorHandler(old_handler);
  272.  
  273.     return got_x_error ? -1 : 0;
  274. }
  275.  
  276. /*
  277.  * LookupName --
  278.  *    Given an interpreter name, see if the name exists in
  279.  *    the interpreter registry for a particular display.
  280.  *
  281.  * Results:
  282.  *    If the given name is registered, return the ID of
  283.  *    the window associated with the name.  If the name
  284.  *    isn't registered, then return 0.
  285.  */
  286.  
  287.     static Window
  288. LookupName(dpy, name, delete, loose)
  289.     Display *dpy;    /* Display whose registry to check. */
  290.     char *name;        /* Name of an interpreter. */
  291.     int delete;        /* If non-zero, delete info about name. */
  292.     char **loose;    /* Do another search matching -999 if not found
  293.                Return result here if a match is found */
  294. {
  295.     unsigned char   *regProp, *entry;
  296.     unsigned char   *p;
  297.     int            result, actualFormat;
  298.     unsigned long   numItems, bytesAfter;
  299.     Atom        actualType;
  300.     Window        returnValue;
  301.  
  302.     /*
  303.      * Read the registry property.
  304.      */
  305.  
  306.     regProp = NULL;
  307.     result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0,
  308.                 MAX_PROP_WORDS, False, XA_STRING, &actualType,
  309.                 &actualFormat, &numItems, &bytesAfter,
  310.                 ®Prop);
  311.  
  312.     if (actualType == None)
  313.     return 0;
  314.  
  315.     /*
  316.      * If the property is improperly formed, then delete it.
  317.      */
  318.  
  319.     if ((result != Success) || (actualFormat != 8) || (actualType != XA_STRING))
  320.     {
  321.     if (regProp != NULL)
  322.         XFree(regProp);
  323.     XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty);
  324.     return 0;
  325.     }
  326.  
  327.     /*
  328.      * Scan the property for the desired name.
  329.      */
  330.  
  331.     returnValue = None;
  332.     entry = NULL;    /* Not needed, but eliminates compiler warning. */
  333.     for (p = regProp; (p - regProp) < numItems; )
  334.     {
  335.     entry = p;
  336.     while ((*p != 0) && (!isspace(*p)))
  337.         p++;
  338.     if ((*p != 0) && (strcmp(name, p + 1) == 0))
  339.     {
  340.         sscanf(entry, "%x", (uint*) &returnValue);
  341.         break;
  342.     }
  343.     while (*p != 0)
  344.         p++;
  345.     p++;
  346.     }
  347.  
  348.     if (loose != NULL && returnValue == None && !IsSerialName(name))
  349.     {
  350.     for (p = regProp; (p - regProp) < numItems; )
  351.     {
  352.         entry = p;
  353.         while ((*p != 0) && (!isspace(*p)))
  354.         p++;
  355.         if ((*p != 0) && IsSerialName(p + 1)
  356.             && (strncmp(name, p + 1, strlen(name)) == 0))
  357.         {
  358.         sscanf(entry, "%x", (uint*) &returnValue);
  359.         *loose = strdup(p + 1);
  360.         break;
  361.         }
  362.         while (*p != 0)
  363.         p++;
  364.         p++;
  365.     }
  366.     }
  367.  
  368.     /*
  369.      * Delete the property, if that is desired (copy down the
  370.      * remainder of the registry property to overlay the deleted
  371.      * info, then rewrite the property).
  372.      */
  373.  
  374.     if ((delete) && (returnValue != None))
  375.     {
  376.     int count;
  377.  
  378.     while (*p != 0)
  379.         p++;
  380.     p++;
  381.     count = numItems - (p-regProp);
  382.     if (count > 0)
  383.         memcpy(entry, p, count);
  384.     XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING,
  385.             8, PropModeReplace, regProp,
  386.             (int) (numItems - (p-entry)));
  387.     XSync(dpy, False);
  388.     }
  389.  
  390.     XFree(regProp);
  391.     return returnValue;
  392. }
  393.  
  394.     static char *
  395. SendEventProc(dpy, eventPtr, expected)
  396.     Display       *dpy;
  397.     XEvent        *eventPtr;        /* Information about event. */
  398.     int            expected;        /* The one were waiting for */
  399. {
  400.     unsigned char   *propInfo;
  401.     unsigned char   *p;
  402.     int            result, actualFormat;
  403.     unsigned long   numItems, bytesAfter;
  404.     Atom        actualType;
  405.  
  406.     if ((eventPtr->xproperty.atom != commProperty)
  407.         || (eventPtr->xproperty.state != PropertyNewValue))
  408.     {
  409.     return;
  410.     }
  411.  
  412.     /*
  413.      * Read the comm property and delete it.
  414.      */
  415.  
  416.     propInfo = NULL;
  417.     result = XGetWindowProperty(dpy, commWindow, commProperty, 0,
  418.                 MAX_PROP_WORDS, True, XA_STRING, &actualType,
  419.                 &actualFormat, &numItems, &bytesAfter,
  420.                 &propInfo);
  421.  
  422.     /*
  423.      * If the property doesn't exist or is improperly formed
  424.      * then ignore it.
  425.      */
  426.  
  427.     if ((result != Success) || (actualType != XA_STRING)
  428.         || (actualFormat != 8))
  429.     {
  430.     if (propInfo != NULL)
  431.     {
  432.         XFree(propInfo);
  433.     }
  434.     return;
  435.     }
  436.  
  437.     /*
  438.      * Several commands and results could arrive in the property at
  439.      * one time;  each iteration through the outer loop handles a
  440.      * single command or result.
  441.      */
  442.  
  443.     for (p = propInfo; (p - propInfo) < numItems; )
  444.     {
  445.     /*
  446.      * Ignore leading NULs; each command or result starts with a
  447.      * NUL so that no matter how badly formed a preceding command
  448.      * is, we'll be able to tell that a new command/result is
  449.      * starting.
  450.      */
  451.  
  452.     if (*p == 0)
  453.     {
  454.         p++;
  455.         continue;
  456.     }
  457.  
  458.     if ((*p == 'r') && (p[1] == 0))
  459.     {
  460.         int        serial, gotSerial;
  461.         char  *res;
  462.  
  463.         /*
  464.          * This is a reply to some command that we sent out.  Iterate
  465.          * over all of its options.  Stop when we reach the end of the
  466.          * property or something that doesn't look like an option.
  467.          */
  468.  
  469.         p += 2;
  470.         gotSerial = 0;
  471.         res = "";
  472.         while (((p-propInfo) < numItems) && (*p == '-'))
  473.         {
  474.         switch (p[1])
  475.         {
  476.             case 'r':
  477.             if (p[2] == ' ')
  478.                 res = p + 3;
  479.             break;
  480.             case 's':
  481.             if (sscanf(p + 2, " %d", &serial) == 1)
  482.                 gotSerial = 1;
  483.             break;
  484.         }
  485.         while (*p != 0)
  486.             p++;
  487.         p++;
  488.         }
  489.  
  490.         if (!gotSerial)
  491.         continue;
  492.  
  493.         return serial == expected ? strdup(res) : NULL;
  494.     }
  495.     else
  496.     {
  497.         /*
  498.          * Didn't recognize this thing.  Just skip through the next
  499.          * null character and try again.
  500.          * Also, throw away commands that we cant process anyway.
  501.          */
  502.  
  503.         while (*p != 0)
  504.         p++;
  505.         p++;
  506.     }
  507.     }
  508.     XFree(propInfo);
  509. }
  510.  
  511. /*
  512.  * AppendPropCarefully --
  513.  *
  514.  *    Append a given property to a given window, but set up
  515.  *    an X error handler so that if the append fails this
  516.  *    procedure can return an error code rather than having
  517.  *    Xlib panic.
  518.  *
  519.  *  Return:
  520.  *    0 on OK - -1 on error
  521.  *--------------------------------------------------------------
  522.  */
  523.  
  524.     static int
  525. AppendPropCarefully(dpy, window, property, value, length)
  526.     Display *dpy;        /* Display on which to operate. */
  527.     Window window;        /* Window whose property is to
  528.                  * be modified. */
  529.     Atom property;        /* Name of property. */
  530.     char *value;        /* Characters  to append to property. */
  531.     int  length;        /* How much to append */
  532. {
  533.     XErrorHandler old_handler;
  534.  
  535.     old_handler = XSetErrorHandler(x_error_check);
  536.     got_x_error = FALSE;
  537.     XChangeProperty(dpy, window, property, XA_STRING, 8,
  538.             PropModeAppend, value, length);
  539.     XSync(dpy, False);
  540.     (void) XSetErrorHandler(old_handler);
  541.     return got_x_error ? -1 : 0;
  542. }
  543.  
  544.  
  545. /*
  546.  * Another X Error handler, just used to check for errors.
  547.  */
  548. /* ARGSUSED */
  549.     static int
  550. x_error_check(dpy, error_event)
  551.     Display *dpy;
  552.     XErrorEvent    *error_event;
  553. {
  554.     got_x_error = TRUE;
  555.     return 0;
  556. }
  557.  
  558. /*
  559.  * Check if name looks like it had a 3 digit serial number appended
  560.  */
  561.     static int
  562. IsSerialName(str)
  563.     char    *str;
  564. {
  565.     if (strlen(str) < 5)
  566.     return FALSE;
  567.     str = str + strlen(str) - 4;
  568.     if (*str++ != '-')
  569.     return FALSE;
  570.     if (!isdigit(*str++))
  571.     return FALSE;
  572.     if (!isdigit(*str++))
  573.     return FALSE;
  574.     if (!isdigit(*str++))
  575.     return FALSE;
  576.  
  577.     return TRUE;
  578. }
  579.